package x7.heatctrl;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.mortbay.util.ajax.JSONObjectConvertor;

import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;

/**
 * keeps a List of last 10 Errors
 * @author Simon
 *
 */
public class Errors {
	
	private static List<Error> errors=new ArrayList<Error>();
	
	/**
	 * logs a error
	 * @param msg
	 * @param ex
	 */
	public static void log(String msg, Exception ex) {
		if (errors.size()>20) errors.remove(0);
		errors.add(new Error(msg, ex));
	}
	
	/**
	 * return all Erros as json.
	 * @return
	 */
	public static JSONArray getErrors() {
		JSONArray res = new JSONArray();
		for (Error e:errors) res.add(e);
		return res;
	}
	
	/**
	 * clears all errors
	 */
	public static void clear() {
		errors.clear();
	}
	
	/** simple Error-struct in order to serialize it as json */
	public static class Error {
		private Date time=new Date();
		private String message;
		private String stackTrace = "";
		
		private Error(String msg, Exception ex) {
			message=msg + " : "+ex;
			if (ex!=null) {
				StringWriter sw = new StringWriter();
				ex.printStackTrace(new PrintWriter(sw));
				stackTrace=sw.toString();
			}
		}
		
		public String getTime() { return time.toString();}
		public String getMessage() { return message; }
		public String getStackTrace() { return stackTrace;}
	}

}
